import { cloneDeep } from "lodash-es";
import { ref } from "vue";

export class BreadCrumb {
  // 唯一键
  key: string = "";
  // 当选显示名称
  name: string = "";
  // 初始化时名称
  initialName: string = "";
  // 当前选中的值
  value: string = "";
  // 初始化时值
  initialValue: string = "";
  order: number = 1;

  constructor(key: string, initialName: string, initialValue: string) {
    this.key = key;
    this.initialName = initialName;
    this.name = initialName;
    this.initialValue = initialValue;
    this.value = initialValue;
  }
}

export const useBreadCrumbs = (initialBradCrumbs?: BreadCrumb[]) => {
  const breadCrumbs = ref<BreadCrumb[]>([]);

  if (initialBradCrumbs && initialBradCrumbs.length) {
    breadCrumbs.value = cloneDeep(initialBradCrumbs);
  }

  const addBreadItem = (
    key: string,
    initialName: string,
    initialValue: string
  ) => {
    if (breadCrumbs.value.length) {
      const keyExist = breadCrumbs.value.findIndex((item) => item.key === key);
      if (keyExist < 0) {
        const newBreadCrumb = new BreadCrumb(key, initialName, initialValue);
        breadCrumbs.value.push(newBreadCrumb);
      }
    } else {
      const newBreadCrumb = new BreadCrumb(key, initialName, initialValue);
      breadCrumbs.value.push(newBreadCrumb);
    }
  };

  const removeBreadIItem = (key: string) => {
    const keyExist = breadCrumbs.value.findIndex((item) => item.key === key);
    if (keyExist > -1) {
      breadCrumbs.value.splice(keyExist, 1);
    }
  };

  const removeBreadIItems = (keys: string[]) => {
    keys.forEach((key) => {
      const keyExist = breadCrumbs.value.findIndex((item) => item.key === key);
      if (keyExist > -1) {
        breadCrumbs.value.splice(keyExist, 1);
      }
    });
  };

  const resetBreadIItem = (key: string) => {
    const target = breadCrumbs.value.find((item) => item.key === key);
    if (target) {
      target.name = target.initialName;
      target.value = target.initialValue;
    }
  };

  const updateBreadIItem = (key: string, name: string, value: string) => {
    const target = breadCrumbs.value.find((item) => item.key === key);
    if (target) {
      target.name = name;
      target.value = value;
    }
  };

  const clearBreadCrumbs = () => {
    breadCrumbs.value = [];
  };

  return {
    breadCrumbs,
    addBreadItem,
    removeBreadIItem,
    removeBreadIItems,
    resetBreadIItem,
    updateBreadIItem,
    clearBreadCrumbs,
  };
};
